"package": "com.jim.notification"
顯示的 package name。"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"package": "com.jim.notification"
},
com.jim.notification
填入。暱稱是選填。然後點擊"註冊應用程式"按鈕,接著下載 google-services.json
檔案。
把下載到的檔案丟到 React 專案裡的 android 資料夾目錄內。
We've added an import for Firebase Messaging:
javascriptCopyimport messaging from '@react-native-firebase/messaging';
We've introduced a new state variable fcmToken to store the FCM token:
javascriptCopyconst [fcmToken, setFcmToken] = useState('');
In the useEffect hook, we've added a call to register for FCM:
javascriptCopyregisterForFCM().then(token => token && setFcmToken(token));
We've added an FCM foreground message handler:
javascriptCopyconst unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('FCM Message received in foreground:', remoteMessage);
// You can show a local notification here if needed
});
We've added a new function registerForFCM() to handle FCM registration:
javascriptCopyasync function registerForFCM() {
let token;
if (Device.isDevice) {
try {
await messaging().registerDeviceForRemoteMessages();
token = await messaging().getToken();
console.log('FCM Token:', token);
} catch (e) {
console.error('Error registering for FCM:', e);
}
}
return token;
}
We're now displaying both the Expo push token and the FCM token in the UI.
To use this setup:
Make sure you have set up Firebase in your project and have the necessary configuration files (google-services.json for Android and GoogleService-Info.plist for iOS).
Install the required dependencies:
Copynpx expo install @react-native-firebase/app @react-native-firebase/messaging
Configure your app.json as mentioned in the previous response, including the googleServicesFile paths.
Use the FCM token (fcmToken) to send push notifications through Firebase Cloud Messaging.